//
//  BaseNavigationController.swift
//  Test
//
//  Created by rui on 2018/5/29.
//  Copyright © 2018年 qewqw. All rights reserved.
//

import UIKit

class NavigationController: UINavigationController {

    func unWrap(vc: UIViewController) -> UIViewController {
        guard let wrapVc = vc as? WrapViewController, let contentVc = wrapVc.contentViewController else { return vc }
        return contentVc
    }
    
    lazy var fullGestureRecongnizer: UIPanGestureRecognizer = {
        let ges = UIPanGestureRecognizer()
        ges.maximumNumberOfTouches = 1
        return ges
    }()
    
    var rui_topViewController: UIViewController? {
        guard let top = self.topViewController else { return nil }
        return unWrap(vc: top)
    }
    
    var rui_viewControllers: [UIViewController] {
        return viewControllers.map({ (vc) -> UIViewController in
            return unWrap(vc: vc)
        })
    }
    
    var target: UIGestureRecognizerDelegate?
    
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    override init(rootViewController: UIViewController) {
        let wrap = WrapViewController()
        wrap.contentViewController = rootViewController
        super.init(rootViewController: wrap)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.setNavigationBarHidden(true, animated: false)
        self.delegate = self
        self.navigationBar.isTranslucent = false
        self.target = self.interactivePopGestureRecognizer?.delegate
    }
    
    
    func handlePopGestureRecognizer(viewController: UIViewController) {
        guard let wrapViewController = viewController as? WrapViewController else {return}
        guard let gesViewController = wrapViewController.contentViewController else { return }
        let isRoot = gesViewController == self.viewControllers.first
        var gess = gesViewController.view.gestureRecognizers
        if let index = gess?.index(of: self.fullGestureRecongnizer) {
            gess?.remove(at: index)
            gesViewController.view.gestureRecognizers = gess
        }
        
        if gesViewController.isInteractivePopGestureRecognizerEnabled == false {
            self.interactivePopGestureRecognizer?.delegate = nil
            self.interactivePopGestureRecognizer?.isEnabled = false
        }else if gesViewController.isFullInteractivePopGestureRecognizerEnabled == false {
            self.interactivePopGestureRecognizer?.delaysTouchesBegan = true;
            self.interactivePopGestureRecognizer?.delegate = self;
            self.interactivePopGestureRecognizer?.isEnabled = !isRoot;
        }else {
            if !isRoot {
                self.interactivePopGestureRecognizer?.view?.addGestureRecognizer(self.fullGestureRecongnizer)
            }
            self.interactivePopGestureRecognizer?.delegate = nil;
            self.interactivePopGestureRecognizer?.isEnabled = false;
            self.fullGestureRecongnizer.delegate = self;
            self.fullGestureRecongnizer.isEnabled = !isRoot;
        }
    }
}

extension NavigationController: UINavigationControllerDelegate,UIGestureRecognizerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        handlePopGestureRecognizer(viewController: viewController)
        NavigationController.attemptRotationToDeviceOrientation()
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if self.rui_viewControllers.count < 2  {
            return false
        }
        return true
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if let _ = gestureRecognizer as? UIScreenEdgePanGestureRecognizer {
            return true
        }
        return false
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if let top = self.topViewController, !top.isInteractivePopGestureRecognizerEnabled {
            return false
        }
        if let isTransitioning = self.navigationController?.value(forKeyPath: "_isTransitioning") as? Bool,isTransitioning {
            return false
        }
        if self.fullGestureRecongnizer == gestureRecognizer {
            let velocityX = self.fullGestureRecongnizer.velocity(in: self.interactivePopGestureRecognizer?.view).x
            if velocityX <= 0 {
                return false
            }
            if let target = self.target {
                let sel = NSSelectorFromString("handleNavigationTransition:")
                self.fullGestureRecongnizer.addTarget(target, action: sel)
            }
            if let top = self.topViewController {
                if top.isFullInteractivePopGestureRecognizerEnabled {
                    let locationX = self.fullGestureRecongnizer.location(in: self.interactivePopGestureRecognizer?.view).x
                    if top.popGestureRecognizerEnabledDistance > 10 && locationX > top.popGestureRecognizerEnabledDistance {
                        return false
                    }
                    return true
                }
            }
        }
        return true
    }
}
